#include "serialclient.h"
#include "io/io.h"
#include "io/serialport.h"
#include "auto/autoclose.h"

SerialClient::SerialClient(QString portName, QObject *parent) :
    QObject(parent),
    mPortName(portName),
    mpSerialPort(nullptr)
{
}

SerialClient::~SerialClient() {
    close();
}

void SerialClient::open() {
    if (!mpSerialPort) {
        mpSerialPort = new SerialPort(mPortName);
        mpSerialPort->open(QIODevice::ReadWrite);
    }
}

void SerialClient::close() {
    if (mpSerialPort) {
        mpSerialPort->close();
        mpSerialPort = nullptr;
    }
}

qint64 SerialClient::send(QByteArray bytes) {
    if (!mpSerialPort) {
        return -1;
    }

    return IO::copy("send", bytes, mPortName, *mpSerialPort, bytes.size());
}

QByteArray SerialClient::recv(qint64 size) {
    if (!mpSerialPort) {
        return QByteArray();
    }

    QByteArray buff;
    IO::copy(mPortName, *mpSerialPort, "recv", buff, size);
    return buff;
}
